package com.sara.loader;

import java.io.InputStream;

import org.apache.http.HttpResponse;

import com.gmcc.tripleplay.app.Constants;
import com.sara.util.ErrorCodeUtils;
import com.sara.util.loader.UrlLoaderParser;

public abstract class ResponseParser extends UrlLoaderParser {

	protected ResponseListener listener;
	protected boolean netResult;

	public ResponseParser(ResponseListener listener) {
		this.listener = listener;
	}

	@Override
	public void doParse(String url, HttpResponse httpresp, InputStream is,
			String postData) {
		netResult = true;
		if ((httpresp == null && !Constants.IS_INTERFACE_TEST) || is == null) {
			response(createFailureResponse(String.valueOf(100)));
			netResult = false;
		} else if (httpresp != null
				&& httpresp.getStatusLine().getStatusCode() != 200) {
			response(createFailureResponse(String.valueOf(httpresp
					.getStatusLine().getStatusCode())));
			netResult = false;
		}
	}

	protected Response createFailureResponse(String tag, String code) {
		Response response = new Response();
		response.setCode(code);
		response.setDescription(ErrorCodeUtils.getErrorDescription(tag,
				String.valueOf(code)));
		return response;
	}

	protected Response createFailureResponse(String code) {
		return createFailureResponse("common", code);
	}

	protected void response(Response response) {
		if (listener != null && response != null) {
			listener.onResponse(response);
		}
	}
}
